<template>
  <div class="weather">
    <slot name="prefix">
      <span style="margin-right: 16px">{{ prefix }}</span>
    </slot>
    <template v-if="weather && weather.temp">
      <img v-if="showIcon && weather.icon" :src="weather.icon" :alt="weather.text" style="height: 2em" />
      <span>{{ weather.text }}</span>
      <span style="margin-left: 16px; font-size: 24px;">{{ weather.temp }}</span>
      <span v-if="weather.temp">℃</span>
    </template>
    <template v-else>
      <a-spin :spinning="true" size="small" />
    </template>
  </div>
</template>

<script>
import axios from 'axios';
import get from 'lodash-es/get.js';

const icons = import.meta.glob('./assets/*.png', { eager: true, import: 'default' });
const iconEnum = Object.keys(icons).reduce((res, key) => {
  const name = key.replace(/\.png$/, '');
  return Object.assign(res, { [name]: icons[key] });
}, {});

export default {
  name: 'weather',
  props: {
    showIcon: { type: Boolean, default: true },
    prefix: { type: String, default: '当前天气' },
    lnglat: { type: String, default: '' },
  },
  data() {
    return {
      weather: {},
    };
  },
  created() {
    this.getWeatherData();
  },
  methods: {
    async getWeatherData() {
      const res = await axios({
        method: 'get',
        url: 'https://devapi.qweather.com/v7/weather/now?key=f3baad3f80b34c3084a079f460d57060&location=' + this.lnglat,
      });
      // console.log(res);
      this.weather = {
        text: get(res, 'data.now.text'),
        temp: get(res, 'data.now.temp'),
        icon: iconEnum[get(res, 'data.now.text')],
      };
    },
  },
};
</script>

<style scoped lang="less">
.weather {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: 400;
  color: #a0a6b1;
}
</style>
